package com.intramirror.product.schedule;

import com.intramirror.product.mapper.PromotionRuleMapper;
import com.intramirror.product.service.IPromotionService;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@PropertySource(value = "classpath:${spring.profiles.active}/schedule.properties")
@Component
public class CampaignSnapshotSchedule {
    private static final Logger LOGGER = LoggerFactory.getLogger(CampaignSnapshotSchedule.class);
    private static final long ONE_MINUTE = 60 * 1000;
    private static int count = 0;

    private static Date lastUpdate = null;

    @Autowired
    PromotionRuleMapper promotionRuleMapper;

    @Autowired
    IPromotionService promotionService;

    @Value("${campaign.refresh.minutes}")
    private Integer snapshotMinutes;

    public Integer getSnapshotMinutes() {
        return snapshotMinutes;
    }

    public void setSnapshotMinutes(Integer snapshotMinutes) {
        this.snapshotMinutes = snapshotMinutes;
    }

    @Scheduled(fixedDelay = ONE_MINUTE)
    public void fixedSnapshotJob() {
        if (count++ % snapshotMinutes != 0) {
            return;
        }

        LOGGER.info("===================================================================");
        LOGGER.info("===================Start to refresh campaign rule=====================");
        LOGGER.info("===================================================================");

        //        Date checkDate = new Date();
        //        if (lastUpdate == null) {
        //            // refresh 所有的更改记录
        //            burstingManager.refreshByDate(null);
        //        } else {
        //            // refresh > lastUpdate 的更改记录
        //            burstingManager.refreshByDate(lastUpdate);
        //        }
        //        lastUpdate = checkDate;

        Long start = System.currentTimeMillis();
        //查询所有需要刷新的promotionId
        List<Map<String, Object>> unRefreshPriceRule = promotionRuleMapper.getUnRefreshCampaignRule();
        LOGGER.info("unRefreshPriceRule list {}.", unRefreshPriceRule);
        if (unRefreshPriceRule.size() > 0) {
            for (Map<String, Object> row : unRefreshPriceRule) {
                try {
                    Long promotionId = Long.valueOf(row.get("promotionId").toString());
                    promotionService.refreshSnapshotProductByPromotion(promotionId);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }
        LOGGER.info("It takes {}ms to refresh campaign rule.", System.currentTimeMillis() - start);
    }
}
